﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Eqwww.Code;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;

namespace Eqwww.Web.Controllers
{
    public class VerifyCodeController : Controller
    {
        private IVerifyCoder _verifyCoder;
        private IMemoryCache _cache;

        public VerifyCodeController(IVerifyCoder verifyCoder, IMemoryCache memoryCache)
        {
            _verifyCoder = verifyCoder;
            _cache = memoryCache;
        }

        public IActionResult Init()
        {
            var code = string.Empty;
            var ms = _verifyCoder.Create(out code, 4);
            code = code.ToLower();
            var token = Guid.NewGuid().ToString();
            ViewBag.token = token;
            Response.Body.Dispose();
            Response.Cookies.Append("verifycode", token);
            _cache.Set(token, code, new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromMinutes(3)));

            return File(ms.ToArray(), @"image/png");
        }
    }
}
